<template>
  <div class="search_container">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
      fixed
      placeholder
    />
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
        @click="selClick(index)"
      >
        <div v-html="item"></div
      ></van-cell>
    </van-cell-group>

    <van-cell-group>
      <van-cell title="搜索历史" />
      <van-cell
        v-for="(item, index) in historiesList"
        :key="index"
        :title="item"
      >
        <template #right-icon>
          <van-icon name="close" class="close-icon" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestionList, getHistories, getSearchList } from "./home";
export default {
  name: "search",
  data() {
    return {
      value: "",
      suggestionList: [],
      historiesList: [],
      searchList: [],
      timeId: null
    };
  },
  methods: {
    onInput() {
      clearTimeout(this.timeId);
      this.timeId = setTimeout(async () => {
        if (this.value == "") {
          this.suggestionList = [];
          return;
        }
        let res = await getSuggestionList({ q: this.value });
        this.suggestionList = res.data.data.options;
      }, 500);
    },
    async onSearch() {
      this.$router.push({
        path: "/searchResult",
        query: { keywords: this.value }
      });
    },
    selClick(index) {
      this.value = this.suggestionList[index];
      this.onSearch();
    }
  },
  async created() {
    let res = await getHistories();
    this.historiesList = res.data.data.keywords;
  },
  computed: {
    // 搜索关键词高亮
    showList() {
      let reg = new RegExp(this.value, "ig");
      return this.suggestionList.map(value =>
        value.replace(reg, match => `<span style="color:red">${match}</span>`)
      );
    }
  }
};
</script>

<style></style>
